package com.zzyl.nursing.service.impl;

import cn.hutool.cache.Cache;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.domain.Room;
import com.zzyl.nursing.mapper.RoomMapper;
import com.zzyl.nursing.service.IRoomService;
import com.zzyl.nursing.vo.BedVo;
import com.zzyl.nursing.vo.DeviceInfo;
import com.zzyl.nursing.vo.RoomVo;
import eu.bitwalker.useragentutils.Utils;
import net.sf.jsqlparser.statement.create.table.RowMovementMode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * 房间Service业务层处理
 *
 * @author ruoyi
 * @date 2024-04-26
 */
@Service
public class RoomServiceImpl extends ServiceImpl<RoomMapper, Room> implements IRoomService {
    @Autowired
    private RoomMapper roomMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    private void removeCache(Long id){
        redisTemplate.opsForHash().delete(CacheConstants.ROOM_PRICE_KEY,id);
    }

    /**
     * 查询房间
     *
     * @param id 房间主键
     * @return 房间
     */
    @Override
    public Room selectRoomById(Long id) {
        return getById(id);
    }

    /**
     * 查询房间列表
     *
     * @param room 房间
     * @return 房间
     */
    @Override
    public List<Room> selectRoomList(Room room) {
        return roomMapper.selectRoomList(room);
    }

    /**
     * 新增房间
     *
     * @param room 房间
     * @return 结果
     */
    @Override
    public int insertRoom(Room room) {
        Set<Object> keys = redisTemplate.opsForHash().keys(CacheConstants.ROOM_PRICE_KEY);
        keys.forEach(x->{
            if(room.getId()==Long.parseLong(x.toString())){
                removeCache(room.getId());
            }
        });

        return save(room) ? 1 : 0;
    }

    /**
     * 修改房间
     *
     * @param room 房间
     * @return 结果
     */
    @Override
    public int updateRoom(Room room) {
        Set<Object> keys = redisTemplate.opsForHash().keys(CacheConstants.ROOM_PRICE_KEY);
        keys.forEach(x->{
            if(room.getId()==Long.parseLong(x.toString())){
                removeCache(room.getId());
            }
        });

        return updateById(room) ? 1 : 0;
    }

    /**
     * 批量删除房间
     *
     * @param ids 需要删除的房间主键
     * @return 结果
     */
    @Override
    public int deleteRoomByIds(Long[] ids) {

        Set<Object> keys = redisTemplate.opsForHash().keys(CacheConstants.ROOM_PRICE_KEY);
        keys.forEach(x->{
            for (Long id : ids) {
                if (id ==Long.parseLong(x.toString())){
                    removeCache(id);
                }
            }
        });
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 根据楼层 id 获取房间视图对象列表
     *
     * @param floorId
     * @return
     */
    @Override
    public List<RoomVo> getRoomsByFloorId(Long floorId) {
        return roomMapper.selectByFloorId(floorId);
    }


    /**
     * 获取所有房间（负责老人）
     *
     * @param floorId
     * @return
     */
    @Override
    public List<RoomVo> getRoomsWithNurByFloorId(Long floorId) {
        return roomMapper.selectByFloorIdWithNur(floorId);
    }


    /**
     * 根据房间id获取房价
     *
     * @param id
     * @return
     */
    @Override
    public RoomVo getRoomById(Long id) {

        // 查询redis缓存
//        Object price = redisTemplate.opsForHash().get(CacheConstants.ROOM_PRICE_KEY, id);
        RoomVo vo = new RoomVo();

        // 如果缓存为空
//        if (Objects.isNull(price) || price==""){
            vo = roomMapper.getRoomById(id);

//            redisTemplate.opsForHash().put(CacheConstants.ROOM_PRICE_KEY,id,vo.getPrice());
//        }
        vo.setId(id);
//        vo.setPrice(price.toString());
        return vo;
    }


    /**
     * 查询房间以及关联的床位和设备
     *
     * @param floorId
     * @return
     */
    @Override
    public List<RoomVo> getRoomsWithDeviceByFloorId(Long floorId) {
        // 获取基础数据
        List<RoomVo> roomVos= roomMapper.getRoomWithDeviceByFloorId(floorId);

        // 获取设备上报数据
        for (RoomVo roomVo : roomVos) {
            List<DeviceInfo> deviceVos = roomVo.getDeviceVos();

            //如果设备列表非空，则遍历处理
            if(CollUtil.isNotEmpty(deviceVos)) {
                for (DeviceInfo deviceVo : deviceVos) {
                    String rdDeviceDataListJSON = (String)redisTemplate.opsForHash().get(CacheConstants.IOT_DEVICE_LAST_DATA, deviceVo.getIotId());
                    if(StringUtils.isNotBlank(rdDeviceDataListJSON)){
                        List<DeviceData> rdDeviceDataList = JSONUtil.toList(rdDeviceDataListJSON, DeviceData.class);

                        //填充设备对应的属性值
                        deviceVo.setDeviceDataVos(rdDeviceDataList);
                    }

                }
            }
            //获取房间下对应的床位列表数据
            List<BedVo> bedVoList = roomVo.getBedVoList();
            //如果床位列表数据非空，则遍历处理
            if(CollUtil.isNotEmpty(bedVoList)) {
                bedVoList.forEach(b-> {
                    //获取床位下的设备列表数据
                    List<DeviceInfo> bdDeviceInfoList = b.getDeviceVos();

                    //如果设备列表数据非空，则遍历处理
                    if (CollUtil.isNotEmpty(bdDeviceInfoList)) {
                        bdDeviceInfoList.forEach(bd -> {
                            //根据设备的IOTID从Redis查询对应的设备数据列表
                            String bdDeviceDataListJSON = (String) redisTemplate.opsForHash().get(CacheConstants.IOT_DEVICE_LAST_DATA, bd.getIotId());
                            if (StringUtils.isNotBlank(bdDeviceDataListJSON)) {
                                List<DeviceData> bdDeviceDataList = JSONUtil.toList(bdDeviceDataListJSON, DeviceData.class);

                                //填充设备对应的属性值
                                bd.setDeviceDataVos(bdDeviceDataList);
                            }
                        });
                    }
                });
            }
        }
        return roomVos;
    }


}
